import { ReactElement, useEffect, useState } from 'react'
import { WorkPerformanceSchema } from '@src/components/schema/performanceSchema'
import { message, Space, Table, Modal } from 'antd'
import style from './index.module.less'
import classNames from 'classnames'
import EditModal from './components/editModal'
import CountModal from './components/countModal'
import { DataSchema, getListRequest, getOtherInfoRequest, updateGradeRequest } from './ajax'
import { getColumn } from './util'
import { awaitWrap } from '@src/assets/js/tool'
import Dictionary, { DictionaryItem } from '@js/dictionary'
import { ExclamationCircleOutlined } from '@ant-design/icons'

const { confirm } = Modal

async function getList (work: WorkPerformanceSchema | null, performanceid: string, setList: (v: DataSchema[]) => void, setLoading: (v: boolean) => void): Promise<void> {
  if (work === null) {
    setList([])
    return undefined
  }
  setLoading(true)
  const [e, d] = await awaitWrap(getListRequest(work, performanceid))
  setLoading(false)
  if (e === null && d instanceof Array) {
    setList(d)
  }
}

// 初始化其他数据
async function initOtherInfo (work: WorkPerformanceSchema | null, performanceid: string, setCount: (v: number) => void, setGrade: (v: string) => void): Promise<void> {
  if (work === null) {
    setCount(0)
    setGrade('')
    return undefined
  }
  const hide = message.loading('加载中', 120)
  const [e, d] = await awaitWrap(getOtherInfoRequest(performanceid, work.accountid))
  hide()
  if (e === null && d !== null) {
    setCount(d.accepter_advise_count)
    setGrade(d.accepter_case_coefficient)
  }
}

// 更新总体表现
async function updateGrade (work: WorkPerformanceSchema | null, performanceid: string, grade: string, refreshData: () => void): Promise<void> {
  if (work === null) {
    return undefined
  }
  const hide = message.loading('提交中', 120)
  const [e] = await awaitWrap(updateGradeRequest(performanceid, work.accountid, grade))
  hide()
  if (e === null) {
    refreshData()
  }
}

// 更新表现二次确认
function confirmGrade (work: WorkPerformanceSchema | null, performanceid: string, d: DictionaryItem, refreshData: () => void): void {
  confirm({
    icon: <ExclamationCircleOutlined />,
    content: `您确定要将总体工作表现更改为 ${d.title} 吗？`,
    onOk () {
      updateGrade(work, performanceid, d.value, refreshData).catch(e => console.error(e))
    }
  })
}

interface Props {
  performanceid: string
  work: WorkPerformanceSchema | null
  refreshFn: () => void
}

function Main ({ work, performanceid, refreshFn }: Props): ReactElement {
  const [visible, setVisible] = useState(false)
  const [countVisible, setCountVisible] = useState(false)
  const [modifyData, setModifyData] = useState<DataSchema | null>(null)
  const [dataSource, setDataSource] = useState<DataSchema[]>([])
  const [loading, setLoading] = useState(false)
  const [count, setCount] = useState(0)
  const [grade, setGrade] = useState('')
  const [grades, setGrades] = useState<DictionaryItem[]>([])
  function refreshData (): void { getList(work, performanceid, setDataSource, setLoading).catch(e => console.error(e)) }
  function refreshOtherData (): void { initOtherInfo(work, performanceid, setCount, setGrade).catch(e => console.error(e)) }
  useEffect(() => {
    const d = new Dictionary()
    d.init('受理秘书总体工作表现')
      .then(() => {
        setGrades(d.getList('受理秘书总体工作表现'))
      })
      .catch(e => console.error(e))
  }, [])
  useEffect(() => {
    refreshData()
    refreshOtherData()
  }, [work])
  return (
    <div className={style.container}>
      <EditModal visible={visible} work={work} performanceid={performanceid} data={modifyData} hide={() => { setVisible(false); setModifyData(null) }} refreshData={() => { refreshData(); refreshFn() }} />
      <CountModal visible={countVisible} work={work} performanceid={performanceid} data={count} hide={() => setCountVisible(false)} refreshData={() => { refreshOtherData(); refreshFn() }} />
      <div className={style['title-line']}>
        <span>受理秘书工作表现</span>
      </div>
      <div className={style['operate-line']}>
        <span>
          咨询次数
          <span className={style.subtitle}>（0.02分/次）</span>
        </span>
        <Space size={24}>
          <a onClick={() => setCountVisible(true)}>选择</a>
          <span>{count}次</span>
        </Space>
      </div>
      <div className={style['operate-line']}>
        <span>工作责任意识，专业水平，服务意识统称为总体工作表现</span>
        <Space size={12}>
          {grades.map((li, i) => {
            return <a key={i} className={classNames(style.grade, { [style.active]: String(grade) === String(li.value) })} onClick={() => confirmGrade(work, performanceid, li, () => { refreshOtherData(); refreshFn() })}>{li.title}</a>
          })}
        </Space>
      </div>
      <div className={style['title-line']}>
        <span>
          撤销/不予执行案件
          <span className={style.subtitle}>（每个扣5分）</span>
        </span>
        <a onClick={() => { setModifyData(null); setVisible(true) }}>添加</a>
      </div>
      <Table rowKey='id' dataSource={dataSource} loading={loading} pagination={false} columns={getColumn(setVisible, setModifyData, () => { refreshData(); refreshFn() })} />
    </div>
  )
}

export default Main
